package com.google.code.porntube.snap.entry;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
import com.google.code.porntube.snap.core.setting.Analyzer;
import com.google.code.porntube.snap.counter.SnapCounter;

public final class GtalkEntry extends HttpServlet {

	private static final long serialVersionUID = 2819445287107488961L;
	
	private void send(XMPPService xmpp, Message message, String txt) {
		Message msg = new MessageBuilder()
		.withRecipientJids(message.getFromJid())
        .withBody(txt)
        .build();

        if (xmpp.getPresence(message.getFromJid()).isAvailable()) {
        	xmpp.sendMessage(msg);
        }
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);		


		send(xmpp, message, "REPORT");
		send(xmpp, message, "__________________");
		send(xmpp, message, "summary:" + "¥r¥n");
		send(xmpp, message, "          total:" + SnapCounter.getCount());
		send(xmpp, message, "           last:" + SnapCounter.getMemo());
		for(String catalog : Analyzer.CATALOG) {
			send(xmpp, message, catalog + ":");
			send(xmpp, message, "          total:" + SnapCounter.getCount(catalog));
			send(xmpp, message, "           last:" + SnapCounter.getMemo(catalog));
		}
		
		
	}
}
